package org.pri.rsa;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;

/**
 * @ClassName: ConvertPkcs1
 * @Description: TODO
 * @Date: 2020/8/25 13:30
 * @Author: ylqiang
 * @Version: 1.0
 */
public class ConvertPkcs {

    @Test
    public void testPkcs8ToPkcs1() throws IOException {
        String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMVewxN43WMj0dymYmmg3WzemdUDvg/+J2kwQvJjkAbDKOs1FciEghqZxiSzA7bdU5pBIdZpCjZaI1XmDbD8uedAOtj1yQ0rEUyQiYEM0WMocOwHnf6y0ACsLlwZS52T5MDt3ligvKh6KCxJYM9QlwdNChxMY5AfxrMKnxVXvJ0BAgMBAAECgYEAoKA2cqpywjRsnv5qKTzZ97hRyaJ6E9nriRfV5B5TIK3Dp2hUihQNLkjnkQZ/h1sopulK+IwT25gQGeBYVCnZwIL2TSCLCnS9ZEhmvU8jUrWGSosLWtjksgxECLS2GuwTcy3hjEEvKNDYdpmND7HV8uQ+yhc5ru5MGs/2eEsuagECQQDy08fyuc499ITxEdppLOUIpq2/cQIlKGzdRui/OiupHEetnlMFL6G7hxhGNZeQ/UYwbYsatjFrVllqqOZzi15ZAkEA0BO0K8K+EDWA09PuuP0lHQVCxKJNg7YxY6rfeiy1mjtTbCeg/dVlqigqT97gXBWG7Zqxkrq9x1DvZW/TufXu6QJBANJpGJUG0+Nzgc6yPaNtN3jrlRqR/d3czZhf3UX2TebXjnSvABk6UNaCFVKhFZiZHrzP7v1SajgsNobpm+b7GOECQCCUBTCY1BNLnTkNRKI4GFh722FYHBTUMNVvCoBhgal9Qml7puw3PiyvDzjkJ3KjeDW5c7YKgO41ENZr9NV32QkCQQDsy9XxEBuafTVsFzWWsOPWsWrbvqQ+YBC0A5IWkM/X03AJvPf8T8YeGQY4oiaGFqrARfQSxnHrDu8cl1qdh0JT";
        byte[] privBytes = Base64.decodeBase64(privateKey);
        PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes);
        ASN1Encodable encodable = pkInfo.parsePrivateKey();
        ASN1Primitive primitive = encodable.toASN1Primitive();
        byte[] privateKeyPKCS1 = primitive.getEncoded();
        String type = "RSA PRIVATE KEY";
        PemObject pemObject = new PemObject(type, privateKeyPKCS1);
        StringWriter stringWriter = new StringWriter();
        PemWriter pemWriter = new PemWriter(stringWriter);
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        String pemString = stringWriter.toString();
        String[] split = pemString.split("-----");
        String replace = split[2].replace("\r\n", "");
        System.out.print(replace);
    }

}
